﻿using System;
using System.Collections.Generic;
using System.Text;
using NoteList.Delegates;
using System.Timers;
using NoteList.EvtArgs;
using NoteList.Models;

namespace NoteList.Biz
{
    public class ZNoteAlarmProvider
    {
        private static ZNoteAlarmProvider _instance = null;
        private Timer _timer = null;
        private ZNotes _notes = null;
        private const int SecScope = 10;

        private ZNoteAlarmProvider(ZNotes notes)
        {
            _notes = notes;
            _timer = new Timer(1000 * SecScope);
            _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
        }

        public static ZNoteAlarmProvider GetInstance(ZNotes notes)
        {
            if (_instance == null)
                _instance = new ZNoteAlarmProvider(notes);
            return _instance;
        }

        public event NoteTimeCame OnNoteTime;

        public void StartTimer()
        {
            _timer.Start();
        }

        public void StopTimer()
        {
            _timer.Stop();
        }

        void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            List<ZNote> comingNotes = new List<ZNote>();
            foreach (ZNote note in _notes)
            {
                if (note.EnableAlarm == true && note.Expired == false && note.AlarmTime <= DateTime.Now && note.AlarmTime > DateTime.Now.AddSeconds(-SecScope))
                {
                    comingNotes.Add(note);
                }
            }
            //IEnumerable<ZNote> comingNotes = _notes.Where(p => p.EnableAlarm == true && p.Expired == false && p.AlarmTime <= DateTime.Now && p.AlarmTime > DateTime.Now.AddSeconds(-SecScope)).OrderBy(p => p.AlarmTime);
            if (comingNotes.Count == 0)
                return;
            NotesEventArgs evt = new NotesEventArgs();
            evt.Notes = ZNotes.CopyFromList(comingNotes);
            OnNoteTime.Invoke(this, evt);
        }
    }
}
